<?php
declare(strict_types=1);

namespace app\admin\model;

use LhpAmis\Renderers\Amis;
use tauthz\facade\Enforcer;

/**
 * 角色管理
 */
class AuthGroupAccess extends Base
{

    protected $name = 'system_auth_group_access';

    /**
     * 创建前
     *
     * @param \think\Model $model
     *
     * @return mixed|void
     */
    public static function onBeforeInsert($model)
    {
        parent::onBeforeInsert($model);
        $model->id = md5(mt_rand(100000, 999999) . microtime());
    }

    /**
     * 创建后
     *
     * @param \think\Model $model
     *
     * @return mixed|void
     */
    public static function onAfterInsert($model)
    {
        Enforcer::addRoleForUser($model->admin_id, $model->group_id);
    }

    /**
     * 删除前
     *
     * @param \think\Model $model
     *
     * @return mixed|void
     */
    public static function onBeforeDelete($model)
    {
        parent::onBeforeDelete($model);
        Enforcer::deleteRoleForUser($model->admin_id, $model->group_id);
    }

    public function getAuths($account_id)
    {
        $data = self::where(['account_id' => $account_id])->findOrEmpty();
        $viewData = [];
        if (!$data->isEmpty()) {
            $admin_ids = [];
            $auth_ids = [];
            $department_ids = [];
            $data = $data->toArray();
            // dump($data);die;
            $data['admin_id'] = array_filter(\explode(',', $data['admin_id']));
            if (!empty($data['admin_id'])) {
                foreach ($data['admin_id'] as $admin_id) {
                    $admin_ids[] = 'a' . $admin_id;
                }
            }
            if (!empty($data['auth_id'])) {
                $data['auth_id'] = array_filter(\explode(',', $data['auth_id']));
                foreach ($data['auth_id'] as $auth_id) {
                    $auth_ids[] = 'r' . $auth_id;
                }
            }
            if (!empty($data['department_id'])) {
                $data['department_id'] = array_filter(\explode(',', $data['department_id']));
                foreach ($data['department_id'] as $department_id) {
                    $department_ids[] = 'd' . $department_id;
                }
            }
            $auth = \array_merge($admin_ids, $auth_ids, $department_ids);
            $viewData['id'] = $account_id;
            $viewData['auth'] = $this->join($auth);
        }

        return $viewData;
    }

    public function TabsTransfer()
    {
        return Amis::make()->TabsTransferControl('access', '权限选择')
            ->sortable('true')
            // ->selectMode('tree')
            ->pickerSize('md')
            ->valueTpl('${label}')
            ->options(
                [
                    $this->getAdmin(),
                    $this->getAuth(),
                    $this->getDepartment(),
                ]
            )
        ;
    }
    public function getGroups(){}
}
